package com.hjy.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class main2 {
    public static ExecutorService threadPool =  Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main---start---");
        // 新建异步任务
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("执行异步方法---");
            int i = 10 / 0;
            System.out.println("执行异步方法完毕");
            return i;
        }, threadPool).handleAsync((integer, throwable) -> {
            System.out.println("handleAsync:integer = " + integer);
            // 这里会爆一个 / zero 的异常, 后续没有 handle 或者 exceptionally 方法, 无法执行thenApplyAsync
            int i = 10 / 0;
            return 300;
        },threadPool).thenApplyAsync(integer -> {
            System.out.println("integer = " + integer);
            return 1024;
        },threadPool);

        // 获取异步任务的最终返回值
        future.get();
        System.out.println("integer = " + future.get());
        System.out.println("main---end---");
    }
    /*
main---start---
执行异步方法---
handleAsync:integer = null
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.ArithmeticException: / by zero
	at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
	at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1908)
	at com.hjy.search.thread.main2.main(main2.java:30)
Caused by: java.lang.ArithmeticException: / by zero
	at com.hjy.search.thread.main2.lambda$main$1(main2.java:22)
	at java.util.concurrent.CompletableFuture.uniHandle(CompletableFuture.java:836)
	at java.util.concurrent.CompletableFuture$UniHandle.tryFire(CompletableFuture.java:811)
	at java.util.concurrent.CompletableFuture$Completion.run(CompletableFuture.java:456)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
     */
}
